package com.etoc.test.util;

import java.net.SocketTimeoutException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

public class HttpUtil {
	
	/**
	 * 
	 * 
	 * @param url
	 * @param nvps
	 * @return
	 * @see 
	 */
	public static String httpRequest(String url, List<NameValuePair> nvps) {
		String respCode = "";
		DefaultHttpClient httpclient = new DefaultHttpClient();
		//
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
		//
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
		
		HttpPost httpPost = new HttpPost(url);
		try {
			//
			httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36");
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			HttpResponse resp = httpclient.execute(httpPost);
			HttpEntity entity = resp.getEntity();
			if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				respCode = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			respCode = "time_out";
		} catch (Exception e) {
			e.printStackTrace();
			respCode = "unknow_error";
		} finally {
			httpPost.releaseConnection();
		}
		return respCode;
	}
	
}
